package system

import (
	"context"
	"time"

	"portal/internal/errorx"
	"portal/internal/svc"
	"portal/internal/tool/auth"
	"portal/internal/types"
	"portal/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type EditPostLogic struct {
	logx.Logger
	ctx       context.Context
	svcCtx    *svc.ServiceContext
	menuModel model.SysMenuModel
	postModel model.SysPostModel
}

func NewEditPostLogic(ctx context.Context, svcCtx *svc.ServiceContext) *EditPostLogic {
	return &EditPostLogic{
		Logger:    logx.WithContext(ctx),
		ctx:       ctx,
		svcCtx:    svcCtx,
		menuModel: model.NewSysMenuModel(svcCtx.Orm),
		postModel: model.NewSysPostModel(svcCtx.Orm),
	}
}

func (l *EditPostLogic) EditPost(req *types.EditPostRequest) (resp *types.CommonResponse, err error) {
	// todo: add your logic here and delete this line
	err = auth.HasPermission(l.menuModel, l.ctx, "system:post:edit")
	if err != nil {
		return nil, errorx.Unauthorized
	}
	post, err := l.postModel.FindOne(l.ctx, req.PostId)
	if err != nil {
		return nil, err
	}
	authinfo,err := auth.GetAuth(l.ctx)
	if err != nil {
		return nil,errorx.AuthNoFound
	}
	if isAdmin,_ := auth.IsAdmin(l.ctx); !isAdmin {
		if err = l.postModel.ExistByPidUid(l.ctx,nil,post.PostId,authinfo.UserId) ; err != nil{
			return nil,errorx.SqlExistError
		}
	}
	if len(req.PostCode) > 0 {
		post.PostCode = req.PostCode
	}
	if len(req.PostName) > 0 {
		post.PostName = req.PostName
	}
	
	if req.PostSort > 0 {
		post.PostSort = req.PostSort
	}
	
	if len(req.Status) > 0 {
		post.Status = req.Status
	}
	post.UpdateBy = authinfo.NickName
	post.UpdateTime = time.Now().Unix()
	err = l.postModel.Edit(l.ctx,nil,post)
	if err != nil {
		return nil,errorx.SqlUpdateError
	}

	return &types.CommonResponse{
		Status: 200,
		Msg: "更新成功",
	},nil
}
